package com.cyzy.controller;

import com.cyzy.dto.Result;
import com.cyzy.pojo.AdminUser;
import com.cyzy.pojo.Menu;
import com.cyzy.pojo.RoleMenu;
import com.cyzy.service.ManageService;

import com.cyzy.service.MenuService;
import com.cyzy.utils.CodeUtils;
import com.cyzy.utils.RedisUtil;
import com.cyzy.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class ManageController {
    //RESTful接口规范：查询用get  增加用post  修改用put  删除用delect
    //登录用post

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private RedisTemplate<String,String> template;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ManageService manageService;

    @Autowired
    private MenuService menuService;

    //管理员登录
    @PostMapping("/login")
    public Result loginUser(@RequestBody AdminUser user, @RequestParam("captcha") String captcha, @RequestParam("key") String key){
        System.out.println(user + " " + "6413541615");
        //判断验证码
        String redisCode = redisUtil.get(key);
        if (redisCode == null || !captcha.equalsIgnoreCase(redisCode)) {
//            System.out.println(redisCode + " " + "99999999999999999999");
            return Result.error().message("验证码有误或已过期！");
        }

        //根据账号查找用户
        AdminUser adminUser = manageService.selectAcc(user.getUsername());
        if (adminUser == null){
            return Result.error().message("账号不存在！");
        }

        //获取密码
        boolean matches = bCryptPasswordEncoder.matches(user.getPassword(), adminUser.getPassword());
        if(!matches){
            return Result.error().message("账号或密码错误！");
        }


//        List<AdminUser> res = manageService.selectUser(user.getUsername(),user.getPassword());
////        System.out.println(res + "" + "68888888888888888884646");
//        if (res.isEmpty()){
////            System.out.println(res + "" + "1111111111111111111111111111111111111");
//            return Result.error().message("账号或密码有误！");
//        }

        String token = TokenUtil.createToken(user.getUsername());
        String redisKey = token;
        redisUtil.set(redisKey, token);
        redisUtil.setExpire(redisKey, 60 * 30); // token有效期 30 分钟
        Map<Object,Object> map = new HashMap<>();
        map.put("user",adminUser);
        map.put("token",token);
        return Result.ok().data("map",map);
    }

    //登录获取路由子菜单
    @GetMapping("/router")
    public Result getRouterMenu(){
        List<Menu> roleMenuList = menuService.selectAllMenuList();
        if (roleMenuList.isEmpty()){
            return Result.error().message("获取菜单列表失败！");
        }
        return Result.ok().data("list",roleMenuList);
    }

    //获取验证码
    @GetMapping("/getcode")
    public Result getCode(String key){
//        System.out.println(key);
        CodeUtils codeUtils = new CodeUtils();
        //获取验证码图片
        String codeBase64 = codeUtils.getRandomCodeImage();

        //获取验证码
        String code = codeUtils.getCode();

        //将验证码存入redis
        redisUtil.set(key, code);
        redisUtil.setExpire(key, 60); // 验证码有效期 1 分钟

        return Result.ok().data("code",codeBase64);
    }

    //对管理员进行添加
    @PostMapping("/add")
    public Result additionalManage(@RequestBody AdminUser adminUser){
//        System.out.println(adminUser + " " + "231843351481515");
        //新增之前，判断该账号有无在数据库中存在
        AdminUser adminUser1 = manageService.selectAcc(adminUser.getUsername());
        if (adminUser1 != null){
            return Result.error().message("该账号已存在，请勿重复添加！");
        }
        //密码加密
        String encode = bCryptPasswordEncoder.encode(adminUser.getPassword());
        adminUser.setPassword(encode);
        int res = manageService.getBaseMapper().insert(adminUser);
//        System.out.println(res);
        if (res == 0){
            return Result.error().message("新增失败！");
        }
        return Result.ok().message("新增成功！");
    }

    //对管理员进行修改
    @PutMapping("/upd")
    public Result updateManage(@RequestBody AdminUser adminUser){
//        System.out.println(adminUser + " " + "262348513516848");

        int res = manageService.updateManage(adminUser.getUsername(),adminUser.getRoleId(),adminUser.getAdminState(),adminUser.getCreateTime());
        if (res == 0){
            return Result.error().message("修改失败！");
        }
        return Result.ok().message("修改成功!");
    }

    //对管理员进行逻辑删除
    @DeleteMapping("/del")
    public Result deleteManage(@RequestParam("adminState") String state,@RequestParam("username") String name){
//        System.out.println(state + " " + name + " " + "561535461");

        int res = manageService.deleteState(name,state);

        if(res != 1){
            return Result.error().message("删除失败！");
        }
        return Result.ok().message("删除成功！");
    }

    //对管理员进行逻辑批量删除
    @DeleteMapping("/dele")
    public Result deleteManage1(@RequestParam("adminState") String state,@RequestParam("adminId") List<String> ids){

        int res = manageService.deleteStateByIds(ids, state); // 调用批量逻辑删除方法

        if (res == 0) {
            return Result.error().message("批量删除失败！");
        }
        return Result.ok().message("成功删除 " + res + " 条记录！");
    }
}
